using Microsoft.AspNetCore.Mvc;
using Blog.Models;
namespace Blog.Controllers;

public class BlogsController : Controller
{
    private readonly BlogDb db;
    public BlogsController()
    {
        db=new BlogDb();
    }
    public IActionResult Index(string oi)
    {


        if(string.IsNullOrEmpty(oi))
        {
             return View(db.Blogs.ToList());
        }
                oi=string.IsNullOrEmpty(oi)?"":oi.Trim();
        var a=db.Blogs.Where(x=>x.Title.Contains(oi)|| x.Content.Contains(oi)|| x.Author.Contains(oi));
        return View(a);

    }

     public IActionResult Delete(int id)
    {
        // 根据id找到对应的blogs，有可能为空
        var blog = db.Blogs.FirstOrDefault(x => x.Id == id);
        return View(blog);
    }

    public IActionResult Deletes(int id)
    {
         var blog = db.Blogs.FirstOrDefault(x => x.Id == id);
         if(blog!=null)
         {
             db.Blogs.Remove(blog);
             db.SaveChanges();
             return RedirectToAction("Index");
         }
        return NotFound();
    }
    
     public IActionResult Add()
    {
        return View();
    }
     [HttpPost]
    public IActionResult Add(Blogs a)
    {
        // var maxId=db.Blogs.Select(x => x.Id).Max();
        // a.Id=maxId+1;

        db.Blogs.Add(a);
        db.SaveChanges();
        return RedirectToAction("Index");
    }
       public IActionResult Edit(int id)
    {
        // 根据id找到对应的blogs，有可能为空
        var blog = db.Blogs.FirstOrDefault(x => x.Id == id);
        return View(blog);
    }

      [HttpPost]
   public IActionResult Edit(Blogs blogs)
   {
    
            // 判断是否有对应的对象 有可能找得到对应id的记录，也有可能找不到
            // 找到后，修改那个对象，然后保存回数据库,返回列表页
      var b=db.Blogs.FirstOrDefault(x=>x.Id==blogs.Id);
      if(b!=null)
      {
        b.Title=blogs.Title;
        b.Content=blogs.Content;
        b.Author=blogs.Author;
        db.SaveChanges();
      }
       // 找不到，直接返回列表页
     
     return  RedirectToAction("Index");
   }



}